'''
Author: SlytherinGe
LastEditTime: 2020-12-12 23:01:04
'''
import torch
import torchvision.models as models
import torch.nn as nn
from torch import Tensor
import torch.nn.init as init

resnet_collections = {
    'resnet50': models.resnet50(),
    'resnet101': models.resnet101(),
    'resnet18': models.resnet18(),
    'resnet34': models.resnet34(),
    'resnet152': models.resnet152()
}

class MyResNet(nn.Module):
    def __init__(self, resnet_type, num_classes):
        super(MyResNet, self).__init__()
        self.layers = []
        resnet = resnet_collections[resnet_type]
        for layer in resnet.children():
            self.layers.append(layer)
        self.conv1 = self.layers[0]
        self.bn1 = self.layers[1]
        self.relu = self.layers[2]
        self.maxpool = self.layers[3]
        self.layer1 = self.layers[4]
        self.layer2 = self.layers[5]
        self.layer3 = self.layers[6]
        self.layer4 = self.layers[7]
        self.avgpool = self.layers[8]
        self.fc1 = nn.Linear(2048, 2048, bias=True)
        self.relu1 = nn.ReLU()
        self.fc2 = nn.Linear(2048, 2048, bias=True)
        self.relu2 = nn.ReLU()
        self.fc3 = nn.Linear(2048, 1024, bias=True)
        self.relu3 = nn.ReLU()
        self.fc4 = nn.Linear(1024, num_classes, bias=True)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.relu1(self.fc1(x))
        x = self.relu2(self.fc2(x))
        x = self.relu3(self.fc3(x))
        out = self.fc4(x)
        return out

def create_resnetX_from_pretrained(resnet_type, num_classes, file_path=None):
    resnet = MyResNet(resnet_type, num_classes)
    init.xavier_normal_(resnet.fc1.weight.detach())
    init.xavier_normal_(resnet.fc2.weight.detach())
    init.xavier_normal_(resnet.fc3.weight.detach())
    init.xavier_normal_(resnet.fc4.weight.detach())
    if file_path is not None:
        model_dict = resnet.state_dict()
        print("loading weights...")
        loaded_dict = torch.load(file_path)
        pretrained_dict = {k: v for k, v in loaded_dict.items() if k in model_dict}
        model_dict.update(pretrained_dict)
        resnet.load_state_dict(model_dict)
        print("weights loaded!")
    print('model created!')
    return resnet

